package com.sunny.ihealth;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.sunny.ihealth.entity.bmob.UserInfo;

import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * Bmob功能管理类
 * Created by Sunny  An on 2016/5/13.
 */
public class BmobManager {

    /**
     * 一个参数的接口
     *
     * @param <T>
     */
    public interface Action1<T> {
        void onCompleted(T t);
    }

    /**
     * 两个参数的接口
     *
     * @param <T>
     * @param <R>
     */
    public interface Action2<T, R> {
        void onCompleted(T t, R r);
    }

    private static final String TAG = "BmobManager";
    private static final String APP_KEY = "2a656c520baa2e8302fd33fbf9b436e6";

    private Context context;
    private Handler handler;

    /**
     * 初始化Bmob
     *
     * @param context
     */
    public BmobManager(Context context) {
        this.context = context;
        handler = new Handler(Looper.getMainLooper());
        Bmob.initialize(this.context, APP_KEY);
    }

    /**
     * 获取错误提示信息
     *
     * @param position 函数位置
     * @param i
     * @param s
     * @return
     */
    private String getErrorMessage(int position, int i, String s) {
        String msg = String.format("error at:%d\ncode:%d\nmessage:%s", position, i, s);
        Log.e(TAG, msg);
        return msg;
    }

    /**
     * 错误toast
     *
     * @param position
     * @param code     错误代码
     * @param s
     */
    private void toast(int position, int code, String s) {
        String message;
        switch (code) {
            case 202:
                message = "账号已存在，换一个账号吧~";
                break;
            case 101:
                message = "账号或密码不正确~";
                break;
            default:
                Toast.makeText(context, getErrorMessage(position, code, s), Toast.LENGTH_SHORT).show();
                return;
        }
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        //打印错误日志
        getErrorMessage(position, code, s);
    }

    /**
     * 注册账号
     *
     * @param username
     * @param password
     */
    public void registerUser(final String username, final String password, final Action1<Boolean> listener) {

        final BmobUser user = new BmobUser();
        user.setUsername(username);
        user.setPassword(password);
        user.signUp(context, new SaveListener() {
            @Override
            public void onSuccess() {
                setDefaultUserInfo(username, listener);
            }

            @Override
            public void onFailure(int i, String s) {
                toast(1, i, s);
                listener.onCompleted(false);
            }
        });

    }


    /**
     * 设置默认资料
     */
    private void setDefaultUserInfo(String username, final Action1<Boolean> listener) {

        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setNickname(username);
        userInfo.setSignature("这家伙很懒，什么都没留下...");
        userInfo.setGender(UserInfo.GENDER_MALE);
        userInfo.save(context, new SaveListener() {
            @Override
            public void onSuccess() {
                listener.onCompleted(true);
            }

            @Override
            public void onFailure(int i, String s) {
                toast(2, i, s);
                listener.onCompleted(false);
            }
        });

    }

    /**
     * 用户登陆
     * 失败UserInfo = null
     *
     * @param username
     * @param password
     * @param listener
     */
    public void login(String username, String password, final Action1<UserInfo> listener) {
        BmobUser user = new BmobUser();
        user.setUsername(username);
        user.setPassword(password);
        user.login(context, new SaveListener() {
            @Override
            public void onSuccess() {
                getLoginUserInfo(listener);
            }

            @Override
            public void onFailure(int i, String s) {
                toast(3, i, s);
                listener.onCompleted(null);
            }
        });
    }

    /**
     * 获取登录用户资料
     *
     * @param listener
     */
    public void getLoginUserInfo(final Action1<UserInfo> listener) {
        BmobUser user = BmobUser.getCurrentUser(context);
        if (user != null && !TextUtils.isEmpty(user.getUsername())) {
            BmobQuery<UserInfo> query = new BmobQuery<>();
            query.addWhereEqualTo("username", user.getUsername());
            query.findObjects(context, new FindListener<UserInfo>() {
                @Override
                public void onSuccess(List<UserInfo> list) {
                    if (list != null && list.size() == 1) {
                        listener.onCompleted(list.get(0));
                    } else {
                        toast(4, 4, "list为空或长度不为0");
                        listener.onCompleted(null);
                    }
                }

                @Override
                public void onError(int i, String s) {
                    toast(5, i, s);
                    listener.onCompleted(null);
                }
            });
        } else {

            handler.post(new Runnable() {
                @Override
                public void run() {
                    toast(6, 5, "获取当前帐号失败");
                    listener.onCompleted(null);
                }
            });
        }

    }

    /**
     * 下线当前账号
     */
    public void logout() {
        BmobUser.logOut(context);
    }


    public void updateUserInfo(String nickname, String signature, boolean gender) {

    }

}
